import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:school_assistant_m/api/login/login_api.dart';
import 'package:school_assistant_m/app/routes/app_pages.dart';
import 'package:school_assistant_m/store/login_store.dart';
import 'package:school_assistant_m/utils/my_toast.dart';

class LoginController extends GetxController {
  //TODO: Implement LoginController
  final LoginApi loginApi = Get.find<LoginApi>();
  // 初始化一个本地存储类LoginStore
  LoginStore store = LoginStore();
  //获取Key用来获取Form表单组件
  GlobalKey<FormState> loginKey = GlobalKey<FormState>();
  //账号和密码输入框
  TextEditingController username = TextEditingController();
  TextEditingController password = TextEditingController();
  //是否显示密码、加载圈
  bool isShowPassWord = false;
  bool isLoading = true;
  //账号和密码表单
  Map loginForm = {
    'username': '',
    'password': '',
  };

  Future<void> isTokenDisabled() async {
    LoginStore store = LoginStore();
    String token = await store.getToken();
    print('---------token================');
    print(token);
    if (token.isEmpty) {
      isLoading = false;
      update(['isLoading']);
      return;
    }
    isLoading = false;
    update(['isLoading']);
  }

  // 从本地磁盘获取用户名密码
  _getLoginInfo() async {
    await isTokenDisabled();
    username.text = await store.getUsername() ?? '';
    password.text = await store.getPassword() ?? '';
  }

  // 执行登录函数
  void handleLogin() {
    var form = loginKey.currentState;
    if (form!.validate()) {
      form.save();
      loginForm['username'] = username.text;
      loginForm['password'] = password.text;
      loginRequest();
    }
  }

  /// 发送登录请求
  Future<void> loginRequest() async {
    Map<String, dynamic> res = await loginApi.login(loginForm);
    // print('--rescode---------------------');
    // print(res['code']);
    switch (res['code']) {
      case 200:
        print(res['data']);
        store.setUserId(res['data']['user_id']);
        store.setToken(res['data']['token']);
        store.setRealname(res['data']['name']);
        store.setUsername(loginForm['username']);
        store.setPassword(loginForm['password']);
        store.setSex(res['data']['user_sex']);
        store.setGrade(res['data']['user_grade']);
        store.setRole(res['data']['user_role']);
        store.setAdmin(res['data']['is_superuser']);
        Get.offNamed(Routes.HOME);
        break;
      case 500:
        MyToast.danger(res['msg']);
        break;
      default:
        MyToast.danger('登录失败,账号或密码错误！');
    }
  }

  // 点击显示密码的的事件
  void showPassWord() {
    isShowPassWord = !isShowPassWord;
    update(['isShowPassWord']);
  }

  @override
  void onInit() {
    super.onInit();
    _getLoginInfo();
  }
}
